package com.zhentao.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhentao.es.service.ApArticleSearchService;
import com.zhentao.es.service.ApUserSearchService;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.es.dto.UserSearchDto;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date 2024/3/9 10:17
 * @Author xdm
 **/
@Service
public class ApArticleSearchServiceImpl implements ApArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {

        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //异步调用，在搜索的时候把搜索记录添加到mongodb里面
        //userId? 参考文章微服务在网关里面根据token获取到userId，存入ThreadLocal里面，然后获取
        //此处先直接写上； admin的id是4
        apUserSearchService.insert(dto.getSearchWords(),4);





        //2.设置查询条件
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();


        //关键字查询
        QueryStringQueryBuilder queryBuilder =
                QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content")
                        .defaultOperator(Operator.OR);


        boolQueryBuilder.must(queryBuilder);

        //查询小于mindate的数据
        if (dto.getMinBehotTime() != null) {

            RangeQueryBuilder rangeQueryBuilder =
                    QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
            boolQueryBuilder.filter(rangeQueryBuilder);
        }

        //分页查询
        builder.from(0);
        builder.size(dto.getPageSize());

        //按照发布时间进行倒叙查询
        builder.sort("publishTime", SortOrder.DESC);

        //设置标题的关键字高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red;'>");
        highlightBuilder.postTags("</font>");

        builder.highlighter(highlightBuilder);


        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println(searchRequest);
        System.out.println(searchResponse);

        //3.结果封装
        List<Map> list = new ArrayList<>();

        SearchHit[] searchHits = searchResponse.getHits().getHits();

        for (SearchHit hit : searchHits) {

            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);

            //!! 前端用的是h_title ,所有需要转换一下
            map.put("h_title",map.get("title"));
            //设置高亮
            //"highlight":{"title":["我是一个<font style='color: red;'>测试</font>标题"]}
            if(hit.getHighlightFields()!=null){
              Text [] texts= hit.getHighlightFields().get("title").getFragments();
              String title=StringUtils.join(texts);
              map.put("h_title",title);
            }


            list.add(map);
        }


        return ResponseResult.okResult(list);
    }
}
